<?php
header('Content-Type: application/json; charset=utf-8');

/* 1. 数据库连接 */
$dbConfig = include('db_config.php');
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '数据库连接失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 2. 取 id */
$id = $_POST['id'] ?? null;
if ($id === null || $id === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => '缺少参数 id'], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 3. 定义 mi_bbs 全部可更新字段（文本形式）*/
$fields = [
    'user_id',     // 发帖用户 id
    'title',       // 帖子标题
    'content',     // 帖子正文
    'category',    // 分类
    'tags',        // 标签
    'attachment',  // 附件链接
    'cover',       // 封面图
    'ip',          // 发帖 IP
    'device',      // 发帖设备
    'extra'        // 扩展字段
];

/* 4. 过滤出需要更新的字段 */
$setParts = [];
$bind = [':id' => $id];

foreach ($fields as $f) {
    if (isset($_POST[$f]) && $_POST[$f] !== '') {
        $key = ':col_' . count($setParts);
        $setParts[] = "`$f` = $key";
        $bind[$key] = $_POST[$f];
    }
}

if (!$setParts) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => '没有任何需要更新的字段'], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 5. 拼接并执行 SQL */
$sql = "UPDATE `mi_bbs` SET " . implode(', ', $setParts) . " WHERE `id` = :id";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($bind);

    echo json_encode([
        'status'  => 'success',
        'message' => '更新成功',
        'updated' => $stmt->rowCount()
    ], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '更新失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
?>
